// 引入链接对象，可以直接封装连接数据库的代码
let conn = require("../utils/myconn.js");
// 获取所有文章数据

// exports.getAllPosts = (obj, callback) => {
//   let sql = `select posts.*,users.nickname,categories.name
//             from posts
//             join users on posts.user_id = users.id
//             join categories on posts.category_id = categories.id
//             order by id desc
//             limit ${(obj.pageNum - 1) * obj.pageSize},${obj.pageSize}`;
//   conn.query(sql, (err, results) => {
//     if (err) {
//       callback(err);
//     } else {
//       callback(null, results);
//     }
//   });
// };

/**
 * 新的需求，需要辨别分类和文章状态。sql语句要加上变化
 */
exports.getAllPosts = (obj, callback) => {
  console.log("进入postsModel");
  // 创建sql语句
  let sql = `SELECT posts.*,users.nickname,categories.name
              FROM posts
              JOIN users on posts.user_id = users.id
              JOIN categories on posts.category_id = categories.id  
              where 1=1 `;
  // 添加和一个恒成立的式子，后面可以通过and来无限添加判断了
  // if (obj.cate && obj.cate != "all") {
  //   sql += ` and category_id = "${obj.cate}"`;
  // }
  // if (obj.status && obj.status != "all") {
  //   sql += ` and posts.status = "${obj.status}"`;
  // }
  sql += ` ORDER BY id DESC
            LIMIT ${(obj.pageNum - 1) * obj.pageSize},${obj.pageSize}`;

  // 获取数据
  conn.query(sql, (err, results) => {
    if (err) {
      callback(err);
    } else {
      // 还有情况，需要对总的文章数量进行查询
      sql = `SELECT count(*) as cnt
              FROM posts
              JOIN users on	 posts.user_id = users.id
              JOIN categories on posts.category_id = categories.id`;
      conn.query(sql, (err2, res2) => {
        if (err2) {
          callback(err2);
        } else {
          callback(null, { data: results, total: res2[0].cnt });
        }
      });
    }
  });
}; /* end getAllPosts */

// exports.addPost = (obj, callback) => {
//   let sql = `insert into posts values(null,"${obj.slug}"`;
//   conn.query(sql, (err, request) => {
//     if (err) {
//       callback(err);
//     } else {
//       callback(results);
//     }
//   });
// };

// 文章新增 0809
// exports.addPost = (obj, callback) => {
//   let sql = `insert into posts values(?)`;
//   conn.query(sql, [obj], (err, results) => {
//     if (err) {
//       callback(err);
//     } else {
//       callback(results);
//     }
//   });
// };

// 根据id获取文章数据
exports.getPostById = (id, callback) => {};

// 根据文章id编辑
exports.editPostById = (obj, callback) => {};
